package com.situ.onlinebookstore.front.controller.api;

import com.github.pagehelper.PageInfo;
import com.situ.onlinebookstore.common.entity.Cart;
import com.situ.onlinebookstore.common.vo.Result;
import com.situ.onlinebookstore.common.entity.User;
import com.situ.onlinebookstore.front.service.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/user/cart")
@RequiredArgsConstructor
public class CartApiController {
    private final CartService cartService;

    //添加购物车
    @PostMapping
    public Result add(@RequestBody Cart cart, HttpSession session){
        //1.参数
        User user = (User) session.getAttribute("user");
        cart.setUserId(user.getId());
        cart.setCount(1); //默认加入一个商品

        //调用Service
        try {
            cartService.add(cart);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @GetMapping
    public Result get(Integer page,Integer limit, HttpSession session){
        //获取当前登录用户的ID
        User user = (User) session.getAttribute("user");
        PageInfo pageInfo = cartService.getByUserId(page,limit,user.getId());
        return Result.ok(pageInfo);
    }

    @GetMapping("/batch")
    public Result get(@RequestParam("cartIds[]") Integer[] cartIds){
        return Result.ok(cartService.getByIds(cartIds));
    }


    @PutMapping
    public Result edit(@RequestBody Cart cart , HttpSession session){
        User user = (User) session.getAttribute("user");
        cart.setUserId(user.getId());
        try {
            cartService.edit(cart);
            cart = cartService.getById(cart.getId());
            return Result.ok(cart);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    @DeleteMapping
    public Result remove(Cart cart , HttpSession session){
        User user = (User) session.getAttribute("user");
        cart.setUserId(user.getId());
        try {
            cartService.remove(cart);
            return Result.ok(cart);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
}
